#!/usr/bin/env python
# encoding: utf-8
"""
freedoor.py
"""

import json
import urllib
import urllib2
import datetime
import httplib2
import urlparse

from httplib2 import Http
from urllib import urlencode

from bottle import route, run, request, debug
from bottle import SimpleTemplate, template
from bottle import static_file
from bottle import TEMPLATE_PATH

# For Testing
from bottle import run

TEMPLATE_PATH = ["./views"]

freedoor_base_url = "http://192.168.1.6:8088/FreeDoor/"

# Routing for static files with ./static
@route('/static/:path#.+#', name='static')
def static(path):
    return static_file(path, root='static')

@route('/')
def default():
	print "Freedoor Default Page"
	message = "Freedoor"

	return template("a_contents", contents=message)


#*************************************************************
#					Communities								 *
#*************************************************************

@route('/communities', method ='GET')
def getCommunities():
	css = ["/static/css/style.css"]
	js = ["/static/js/show_communities.js"]
	
	return template("communities", css=css, js=js)

@route('/getcommunities.json')
def getCommunities():
	url = urlparse.urljoin(freedoor_base_url, "communities")
	
	h = httplib2.Http(".cache")
	resp, content = h.request(url, "GET")
	
	return json.loads(content)

#*************************************************************
#						Goods								 *
#*************************************************************

@route('/goods', method ='GET')
def getGoods():
	css = ["/static/css/style.css"]
	js = ["/static/js/show_goods.js"]
	
	return template("goods", css=css, js=js)

@route('/getgoods.json')
def aj_getGoods():
	url = urlparse.urljoin(freedoor_base_url, "goods")
	h = httplib2.Http(".cache")
	resp, content = h.request(url, "GET")
	
	return json.loads(content)

@route('/addgoods', method ='GET')
def postGoods():
	return template("goods_add")

@route('/addgoods', method ='POST')
def postGoods():
	url = urlparse.urljoin(freedoor_base_url, "goods")
	dt = datetime.datetime.now()
	http = Http()
	
	data = dict(
				community_url = request.forms.get('community_url'),
				id = request.forms.get('id'),
				name = request.forms.get('title'),
				type = "goods",
				description = request.forms.get('description'),
				status = request.forms.get('status'),
				timestamp = dt.strftime("%d/%m/%Y %H:%M")
				)

	headers = {'Content-type': 'application/json', 'session-token': 'theadjs'}
	resp, content = http.request(url, "POST", headers=headers, body=json.dumps(data))
	
	print resp
	print content

	if(resp["status"] == "200"):
		message = "Post Sucessful"
	else:
		message = "Post Failed"
	
	return template("a_contents", contents=message)

@route('/getgoods', method ='GET')
def getGoodsId():
	return template("goods_get_form_id")

@route('/showgoods', method = 'POST')
def showServiceID():
	id = request.forms.get('id')
	print "showgoods id: " + id
	css = ["/static/css/style.css"]
	js = []
	
	return template("goods_show_id", js=js, css=css, goods_id=id)

@route('/getgoods/<id>', method = 'GET')
def getGoodsId(id):
	url = urlparse.urljoin(freedoor_base_url, "goods")

	url = url + "/" + str(id)

	h = httplib2.Http(".cache")
	resp, content = h.request(url, "GET")
	
	print resp
	print content
	return json.loads(content)

@route('/updategoods', method = 'GET')
def putGoodsId():
	return template("goods_put")

@route('/updategoods', method = 'POST') # 'PUT' goods
def putGoodsId():
	url = urlparse.urljoin(freedoor_base_url, "goods")
	dt = datetime.datetime.now()
	http = Http()

	id = request.forms.get('id')
	url = url + "/" + str(id)
	data = dict(
				community_url = request.forms.get('community_url'),
				id = request.forms.get('id'),
				name = request.forms.get('title'),
				type = "goods",
				description = request.forms.get('description'),
				status = request.forms.get('status'),
				timestamp = dt.strftime("%d/%m/%Y %H:%M")
				)
	
	headers = {'Content-type': 'application/json', 'session-token': 'theadjs'}
	resp, content = http.request(url, "PUT", headers=headers, body=json.dumps(data))
	
	print json.dumps(data)
	print resp
	print content

	if(resp["status"] == "200"):
		message = "Update Sucessful"
	else:
		message = "Update Failed"

	return template("a_contents", contents=message)

@route('/deletegoods', method = 'GET')
def deleteGoodsId():
	return template("goods_delete")

@route('/deletegoods', method ='POST') # 'DELETE goods
def deleteGoodsId():
	url = urlparse.urljoin(freedoor_base_url, "goods")
	http = Http()
	
	id = request.forms.get('id')
	url = url + "/" + str(id)
	
	headers = {'Content-type': 'application/json', 'session-token': 'theadjs'}
	resp, content = http.request(url, "DELETE", headers=headers)
	
	print resp
	print content

	if(resp["status"] == "200"):
		message = "Delete Sucessful"
	else:
		message = "Delete Failed"

	return template("a_contents", contents=message)

@route('/goods/search', method = 'GET')
def searchGoods():
	return template("goods_search_form")

@route('/goods/search_results', method = 'POST')
def showGoodssSearchResults():
	css = ["/static/css/style.css"]
	js = []
	keywords = request.forms.get('keywords') # XXX may need to parse this
	
	return template("goods_search_show", js=js, css=css, keywords=keywords)

@route('/goods/searchgoods/<keywords>', method = 'GET')
def searchGoods(keywords):
	url = urlparse.urljoin(freedoor_base_url, "goods/search?")
	http = Http()
	
	data = dict(
				name = keywords,
				page = 1
				)
	
	url_parts = list(urlparse.urlparse(url))
	query = dict(urlparse.parse_qsl(url_parts[4]))
	query.update(data)
	url_parts[4] = urllib.urlencode(query)
	
	print urlparse.urlunparse(url_parts)
	
	resp, content = http.request(urlparse.urlunparse(url_parts), "GET")
	print resp
	print content
	
	return json.loads(content)

# Submit Offers on Goods
@route('/offersgoods', method = 'GET')
def offersGoods():
	return template("goods_offers_form")

#@route('/getoffersgoods', method = 'POST')
#def aj_getOffersGoods():
#	url = urlparse.urljoin(freedoor_base_url, "goods")
#	id = request.forms.get('id')
#	url = url + "/" + str(id) + "/offers"
#	
#	h = httplib2.Http(".cache")
#	resp, content = h.request(url, "GET")
#
#	return json.loads(content)

@route('/submitoffersgoods', method ='POST')
def offersGoods():
	url = urlparse.urljoin(freedoor_base_url, "goods")
	http = Http()
	
	item_id = request.forms.get('id')
	url = url + "/" + item_id + "/offers"

	# construct 'id' = node_id + services + item_id
	offer_node_url = "http://" + request.forms.get('node_name') + "/FreeDoor/goods/" + item_id

	data = dict(
			message = request.forms.get('message'),
			email = request.forms.get('email'),
			id = offer_node_url								# id: http://anothernode/FreeDoor/goods/12345
			)

	headers = {'Content-type': 'application/json', 'session-token': 'theadjs'}
	resp, content = http.request(url, "POST", headers=headers, body=json.dumps(data))
	
	print resp
	print content

	if(resp["status"] == "200"):
		message = "Offer Sucessfully Submitted"
	else:
		message = "Offer Failed To Submit"
	
	return template("a_contents", contents=message)

# Show Offers on Existing Goods
@route('/showoffersgoods', method = 'GET')
def showOffersGoods():
	return template("goods_offers_form")

@route('/showoffersgoods', method = 'POST')
def showOffersServices():
	css = ["/static/css/style.css"]
	js = []
	item_id = request.forms.get('id')
	
	return template("goods_offers_show", js=js, css=css, item_id=item_id)

@route('/getoffersgoods/<item_id>', method = 'GET')
def aj_showOffersServices(item_id):
	url = urlparse.urljoin(freedoor_base_url, "goods")
	
	url = url + "/" + item_id + "/offers"
	h = httplib2.Http(".cache")
	resp, content = h.request(url, "GET")
	
	print resp
	print content
	
	if(resp["status"] == "500"):
		message = "Not a Valid ID"
		return template("a_contents", contents=message)
	elif(content == ""):
		message = "Returned Null Value"
		return template("a_contents", contents=message)
	else:
		return json.loads(content)

#*************************************************************
#						Services							 *
#*************************************************************

@route('/services', method = 'GET')
def getServices():
	url = urlparse.urljoin(freedoor_base_url, "services")
	css = ["/static/css/style.css"]
	js = ["/static/js/show_services.js"]		
				
	return template("services", css=css, js=js)

@route('/getservices.json')
def aj_getGoods():
	url = urlparse.urljoin(freedoor_base_url, "services")
	h = httplib2.Http(".cache")
	resp, content = h.request(url, "GET")
	
	print resp
	print content
	
	return json.loads(content)

@route('/addservices', method ='GET')
def postServices():
	url = urlparse.urljoin(freedoor_base_url, "services")

	return template("services_add")

@route('/addservices', method = 'POST')
def postServices():
	url = urlparse.urljoin(freedoor_base_url, "services")
	dt = datetime.datetime.now()
	http = Http()

	data = dict(
				community_url = request.forms.get('community_url'),
				id = request.forms.get('id'),
				name = request.forms.get('title'),
				type = "services",
				description = request.forms.get('description'),
				status = request.forms.get('status'),
				timestamp = dt.strftime("%d/%m/%Y %H:%M")
				)
	
	headers = {'Content-type': 'application/json', 'session-token': 'theadjs'}
	resp, content = http.request(url, "POST", headers=headers, body=json.dumps(data))

	print resp
	print content

	if(resp["status"] == "200"):
		message = "Post Sucessful"
	else:
		message = "Post Failed"

	return template("a_contents", contents=message)

@route('/getservices', method ='GET')
def getServicessID():
	return template("services_get_form_id")

@route('/showservice', method = 'POST')
def showServiceID():
	id = request.forms.get('id')
	css = ["/static/css/style.css"]
	js = []
	
	print "id: " + str(id)

	return template("services_show_id", js=js, css=css, service_id=id)

@route('/getservices/<id>', method ='GET')
def getServicesId(id):
	url = urlparse.urljoin(freedoor_base_url, "services")
	url = url + "/" + str(id)
	
	h = httplib2.Http(".cache")
	resp, content = h.request(url, "GET")
	
	print url
	print resp
	print content
	return json.loads(content)

@route('/updateservices', method = 'GET')
def putServicesId():
	return template("services_put")

@route('/updateservices', method ='POST') # 'PUT' services
def putServicesId():
	url = urlparse.urljoin(freedoor_base_url, "services")
	dt = datetime.datetime.now()
	http = Http()
	
	id = request.forms.get('id')
	url = url + "/" + str(id)
	data = dict(
				community_url = request.forms.get('community_url'),
				id = request.forms.get('id'),
				name = request.forms.get('title'),
				type = "services",
				description = request.forms.get('description'),
				status = request.forms.get('status'),
				timestamp = dt.strftime("%d/%m/%Y %H:%M")
				)
	
	headers = {'Content-type': 'application/json', 'session-token': 'theadjs'}
	resp, content = http.request(url, "PUT", headers=headers, body=json.dumps(data))
	
	print resp
	print content

	if(resp["status"] == "200"):
		message = "Update Sucessful"
	else:
		message = "Update Failed"

	return template("a_contents", contents=message)

@route('/deleteservices', method = 'GET')
def deleteServicesId():
	return template("services_delete")

@route('/deleteservices', method ='POST') # 'DELETE services
def deleteServicesId():
	url = urlparse.urljoin(freedoor_base_url, "services")
	http = Http()
	
	id = request.forms.get('id')
	url = url + "/" + str(id)
	
	print url
	
	headers = {'Content-type': 'application/json', 'session-token': 'theadjs'}
	resp, content = http.request(url, "DELETE", headers=headers)
	
	print resp
	print content

	if(resp["status"] == "200"):
		message = "Delete Sucessful"
	else:
		mesage = "Delete Failed"

	return template("a_contents", contents=message)

@route('/services/search', method = 'GET')
def searchServices():
	return template("services_search_form")

@route('/services/search_results', method = 'POST')
def showServicesSearchResults():
	css = ["/static/css/style.css"]
	js = []
	keywords = request.forms.get('keywords') # XXX may need to parse this
		
	return template("services_search_show", js=js, css=css, keywords=keywords)

@route('/services/searchservices/<keywords>', method ='GET')
def searchServices(keywords):
	url = urlparse.urljoin(freedoor_base_url, "services/search?")
	http = Http()
	
	data = dict(
				name = keywords,
				page = 1
				)
	
	url_parts = list(urlparse.urlparse(url))
	query = dict(urlparse.parse_qsl(url_parts[4]))
	query.update(data)
	
	url_parts[4] = urllib.urlencode(query)
	
	print urlparse.urlunparse(url_parts)
	
	#headers = {'Content-type': 'application/json'}
	resp, content = http.request(urlparse.urlunparse(url_parts), "GET")

	#print urlencode(data)
	
	#print resp
	#print content
	
	return json.loads(content)

# Submit Offers on Services
@route('/offersservices', method = 'GET')
def offersServices():
	return template("services_offers_form")

#@route('/getoffersservices', method = 'POST')
#def aj_offersServices():
#	url = urlparse.urljoin(freedoor_base_url, "services")
#	id = request.forms.get('id')
#	url = url + "/" + str(id) + "/offers"
#	
#	h = httplib2.Http(".cache")
#	resp, content = h.request(url, "GET")
#	
#	return json.loads(content)

@route('/submitoffersservices', method ='POST')
def offersServices():
	url = urlparse.urljoin(freedoor_base_url, "services")
	http = Http()
	
	item_id = request.forms.get('id')
	url = url + "/" + item_id + "/offers"
	
	# construct 'id' = node_id + services + item_id
	offer_node_url = "http://" + request.forms.get('node_name') + "/FreeDoor/services/" + item_id

	data = dict(
			message = request.forms.get('message'),
			email = request.forms.get('email'),
			id = offer_node_url								# id: http://anothernode/FreeDoor/services/12345
			)
	
	headers = {'Content-type': 'application/json', 'session-token': 'theadjs'}
	resp, content = http.request(url, "POST", headers=headers, body=json.dumps(data))
	
	print resp
	print content

	if(resp["status"] == "200"):
		message = "Offer Sucessfully Submitted"
	else:
		message = "Offer Failed To Submit"

	return template("a_contents", contents=message)

# Show offers on Existing Service
@route('/showoffersservices', method = 'GET')
def showOffersServices():
	return template("services_offers_form")

@route('/showoffersservices', method = 'POST')
def showOffersServices():
	css = ["/static/css/style.css"]
	js = []
	service_id = request.forms.get('id')
	print service_id
	return template("services_offers_show", js=js, css=css, service_id=service_id)

@route('/getoffersservices/<service_id>', method = 'GET')
def aj_showOffersServices(service_id):
	url = urlparse.urljoin(freedoor_base_url, "services")

	url = url + "/" + service_id + "/offers"
	h = httplib2.Http(".cache")
	headers = {'session-token': 'theadjs'}
	resp, content = h.request(url, "GET", headers=headers)
	
	print url
	print resp
	print content
	
	if(resp["status"] == "500"):
		message = "Not a Valid ID"
		return template("a_contents", contents=message)
	elif(content == ""):
		message = "Returned Null Value"
		return template("a_contents", contents=message)
	else:
		return json.loads(content)

run(host='localhost', port=8088, reloader=True)

